<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-05-06 14:53
 *
 * 项目：upload  -  $  - Adminv.php
 *
 * 作者：liwei 
 */

namespace lev\base;

use Lev;
use lev\controllers\LoginController;
use lev\helpers\cacheFileHelpers;
use lev\helpers\ModulesHelper;
use modules\levs\modules\admin\controllers\DefaultController;
use modules\levs\modules\admin\helpers\adminSetHelper;
use modules\levs\modules\usergroups\helpers\usergroupsInterfaceHelper;

!defined('INLEV') && exit('Access Denied LEV');


class Adminv
{
    public static $apiCheck = null;

    public static function checkAccess() {
        if (!static::isAdmin()) {
            static::checkAdminPwd();
            if (ModulesHelper::isInstallModule('admin')) {
                DefaultController::actionLogin();
            }
            Lev::showMessages('抱歉，您没有管理权限');
        }
        defined('INADMINLEV') || define('INADMINLEV', 1);
    }

    public static function isAdmin() {
        return Lev::$app['isAdmin'] ?: (static::apiCheck() ?: (static::adminUids() ?: static::isAdminGroup()));
    }

    public static function definedISAPI() {
        defined('ISAPI') || define('ISAPI', 1);
    }

    /**
     *
     * @param null $pwd
     * @see adminSetHelper::openAdminPwd()
     */
    public static function checkAdminPwd($pwd = null) {
        if (static::$apiCheck) return;

        $pwd === null && $pwd = Lev::stripTags(Lev::GPv('adminPwd'));
        $cKey = 'superman_pwd';
        $openPwd = trim(Lev::stget('openAdminPwd', 'admin'));
        $setPwd = trim(Lev::stget('adminPwd', 'admin'));
        if (!$openPwd && $setPwd) {
            $cPwd = $pwd ?: Lev::opCookies($cKey);
            if ($cPwd != $setPwd) {
                exit('404');
            };
            Lev::opCookies($cKey, $setPwd, 3600);
        }
    }

    /**
     * levs 模块管理员为全局 其它模块为内部管理员 仅限模块内
     * @return bool
     */
    public static function adminUids() {
        if (isset(Lev::$app['isAdminModule'])) {
            return false;
        }
        Lev::$app['isAdminModule'] = false;
        if (Lev::$app['uid'] <1) {
            return false;
        }
        $iden = Lev::stripTags(Lev::GPv('iden'));
        $iden = $iden && Controllerv::$route === 'superman/settings' ? $iden : Lev::$app['iden'];
        if ($uids = Lev::stgetv('adminUids', $iden)) {
            $uidarr = explode('=', $uids);
            foreach ($uidarr as $uid) {
                $uid = intval($uid);
                $uid >= 1 && $result[$uid] = $uid;
            }
            return Lev::$app['isAdminModule'] = !empty($result[Lev::$app['uid']]);
        }
        return false;
    }

    /**
     * @see usergroupsInterfaceHelper::isAdmin()
     */
    public static function isAdminGroup() {
        !isset(Lev::$app['isAdminGroup']) &&
        Lev::$app['isAdminGroup'] = Lev::actionObjectMethodIden('usergroups', 'modules\levs\modules\usergroups\helpers\usergroupsInterfaceHelper', [], 'isAdmin');
        return is_numeric(Lev::$app['isAdminGroup']);
    }

    /**
     * 仅针对后台 ，前台放行
     * @return bool|mixed
     */
    public static function isView() {
        if (defined('INADMINLEV')) {
            return Lev::$app['isAdmin'] ?: Lev::actionObjectMethodIden('usergroups', 'modules\levs\modules\usergroups\helpers\usergroupsInterfaceHelper', [], 'isView');
        }
        return true;
    }

    public static function isEdit() {
        if (defined('INADMINLEV')) {
            return Lev::$app['isAdmin'] ?: Lev::actionObjectMethodIden('usergroups', 'modules\levs\modules\usergroups\helpers\usergroupsInterfaceHelper', [], 'isEdit');
        }
        return true;
    }

    public static function isDelete() {
        if (defined('INADMINLEV')) {
            return Lev::$app['isAdmin'] ?: Lev::actionObjectMethodIden('usergroups', 'modules\levs\modules\usergroups\helpers\usergroupsInterfaceHelper', [], 'isDelete');
        }
        return true;
    }

    public static function isAdd() {
        if (defined('INADMINLEV')) {
            return Lev::$app['isAdmin'] ?: Lev::actionObjectMethodIden('usergroups', 'modules\levs\modules\usergroups\helpers\usergroupsInterfaceHelper', [], 'isAdd');
        }
        return true;
    }

    public static function apiCheck() {
        if (static::$apiCheck !== null) {
            return static::$apiCheck;
        }

        static::$apiCheck = false;

        if ($adminSign = Lev::GETv('adminSign')) {
            $timestamp = floatval(Lev::GPv('timestamp'));
            if ($timestamp < Lev::$app['timestamp'] - 3600 * 24) {
                Lev::GETv('showErr') && exit('管理签名超时'.$timestamp.'--'.Lev::$app['timestamp'].'！或是超出POST最大数据限制');
            }else {
                //$pwd = Lev::stgetv('adminPwd', Lev::$app['iden']);
                $pwd = Lev::actionObjectMethod('modules\\'.Modulesv::getIdenNs(Lev::$app['iden']).'\\'.Lev::$app['iden'].'Helper', [], 'adminPwd');
                if ($pwd) {
                    if (static::getAdminSign($pwd, $timestamp) === $adminSign) {
                        static::definedISAPI();
                        static::$apiCheck = true;
                    }else {
                        Lev::GETv('showErr') && exit('错误的管理签名');
                    }
                }
            }
        }

        return static::$apiCheck;
    }

    public static function getAdminSign($adminPwd, $timestamp) {
        return md5($adminPwd . '123o0' . $timestamp);
    }


    /**
     * @param bool $checkToken
     * @return bool|mixed|string
     *
     * @see LoginController::actionCheckTempToken()
     */
    public static function getTemporaryAccesstoken($checkToken = false, $key = 'tempToken=') {
        $ckey = 'getTemporaryAccesstoken';
        if ($checkToken) {
            $token = cacheFileHelpers::getc($ckey);
            cacheFileHelpers::clearc($ckey);
            return $token === $checkToken;
        }
        if (Lev::$app['isAdmin']) {
            $token = static::getAdminSign(Lev::$app['timestamp'], Lev::$app['timestamp']);
            cacheFileHelpers::setc($ckey, $token, 300);
            return $key.$token;
        }
        return false;
    }
}